<template>

  <el-form ref="deptForm" :rules="formRules" :model="form" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getsimple } from '@/api/employees'
import { addDepartments, getDepartmentsDetail, getDepartmentsPut } from '@/api/departments'
export default {
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    const validaCod = (rule, value, callback) => {
    // 验证用户输入的value值 ,在整个项目中的编码是否已经存在
    // - 获取整个部门的编码 编码的数组
      let existList = this.originList.map(item => item.code)
      // - 如果是编辑的状态 , 将当前的部门的编码从存在的数组中移除 , 然后再判断

      if (this.isEdit) {
        existList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      if (existList.includes(value)) {
        callback(new Error(`该部门编码${value}已存在,请换一个编码`))
      } else {
        // 不存在则校验通过
        callback()
      }
    }
    const validaName = (rule, value, callback) => {
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log('existNameList', existNameList)
      if (this.isEdit) {
        // 只能获取到当前编辑的部门 , 获取到当前编辑部门的pid
        const pid = this.originList.find(item => item.id).pid
        // 通过pid去所有的部门数据中找当前的编辑部门的所有兄弟
        const brothers = this.originList.filter(item => item.pid === pid)
        // 排除自己
        existNameList = brothers.filter(item => item.id !== this.id).map(item => item.name)
      }
      // - 判断当前用户输入的value , 在被列表中占用是否存在
      if (existNameList.includes(value)) {
        callback(new Error(`该部门名称${value}已存在,请更换名称`))
      } else {
        // 名称不一样时,直接通过
        callback()
      }
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      formRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 3, max: 50, message: '请输入3~50字以内的部门名称', trigger: 'blur' },
          { validator: validaName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 3, max: 50, message: '请输入3~50字以内的部门编码', trigger: 'blur' },
          { validator: validaCod, trigger: 'blur' }
        ],
        manager: [{ required: true, message: '请输入部门负责人', trigger: 'blur' }],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 3, max: 30, message: '请输入3~30字以内的部门介绍', trigger: 'blur' }
        ]
      },
      list: []

    }
  },
  // 侦听组件内props中属性或者data函数中属性的变化
  watch: {
    id: function(newVal, oldVal) {
      console.log(newVal)
      console.log(oldVal)
      // 方法三 : 解决数据不更新的问题
      this.loadDepartmentsDetail()
    }
  },
  created() {
    this.loadsimple()
    if (this.isEdit) {
      this.loadDepartmentsDetail()
    }
  },
  methods: {
    // 在子组件中定义重置表单的方法 resetFields 重置整个表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    async doEdit() {
      try {
        await getDepartmentsPut(this.form)
        // 重新渲染 , 关闭弹层
        this.$emit('transmit')
      } catch (error) {
        console.log(error)
      }
    },
    async loadDepartmentsDetail() {
      try {
        const res = await getDepartmentsDetail(this.id)
        console.log('getDepartmentsDetail', res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    async  doAdd() {
      try {
        // this.form 中缺少pid , 获取pid
        const res = await addDepartments({ pid: this.id, ...this.form })
        console.log('restwo', res)
        this.$emit('transmit')
      } catch (error) {
        console.log(error)
      }
    },
    async  loadsimple() {
      try {
        await getsimple(this.form)
      } catch (error) {
        console.log(error)
      }
    },
    // 确定
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        // 判断失败
        if (!valid) return
        //   // 封装一个函数
        // this.isEdit ? '编辑' : '新增'
        this.isEdit ? this.doEdit() : this.doAdd()
        //
      })
    },
    // 取消
    hCancel() {
      // 点击取消关闭弹层
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
